package com.cruise.game.service.impl.admin;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cruise.game.common.api.ApiException;
import com.cruise.game.common.constants.CacheConstants;
import com.cruise.game.common.utils.RedisUtils;
import com.cruise.game.mapper.AnnouncementMapper;
import com.cruise.game.model.entity.Announcement;
import com.cruise.game.model.param.admin.AnnouncementCreateParam;
import com.cruise.game.model.vo.admin.AnnouncementVO;
import com.cruise.game.model.vo.common.PageResult;
import com.cruise.game.service.admin.AdminAnnouncementService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 管理员通告服务实现
 * 
 * @author cruise
 * @date 2025-02-28
 */
@Slf4j
@Service
public class AdminAnnouncementServiceImpl implements AdminAnnouncementService {

    @Resource
    private AnnouncementMapper announcementMapper;

    @Resource
    private RedisUtils redisUtils;

    @Override
    public PageResult<AnnouncementVO> getAnnouncementList(String status, Integer page, Integer pageSize) {
        // 构建查询条件
        LambdaQueryWrapper<Announcement> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(status)) {
            queryWrapper.eq(Announcement::getStatus, status);
        }
        queryWrapper.orderByDesc(Announcement::getCreatedAt);

        // 计算总记录数
        long count = announcementMapper.selectCount(queryWrapper);

        // 计算偏移量
        long offset = (page - 1) * pageSize;

        // 修改：自定义分页，避免MyBatis Plus自动生成的带两个LIMIT的SQL
        queryWrapper.last("LIMIT " + offset + ", " + pageSize);
        List<Announcement> announcements = announcementMapper.selectList(queryWrapper);

        // 转换为VO
        List<AnnouncementVO> announcementVOs = new ArrayList<>();
        for (Announcement announcement : announcements) {
            AnnouncementVO vo = new AnnouncementVO();
            BeanUtils.copyProperties(announcement, vo);
            announcementVOs.add(vo);
        }

        // 构建分页结果
        return PageResult.of(announcementVOs, count, page, pageSize);
    }

    @Override
    public AnnouncementVO getAnnouncementDetail(Long id) {
        // 查询通告信息
        Announcement announcement = announcementMapper.selectById(id);
        if (announcement == null) {
            throw new ApiException("通告不存在");
        }

        // 构建通告VO
        AnnouncementVO announcementVO = new AnnouncementVO();
        BeanUtils.copyProperties(announcement, announcementVO);

        return announcementVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createAnnouncement(AnnouncementCreateParam param) {
        // 构建通告对象
        Announcement announcement = new Announcement();
        BeanUtils.copyProperties(param, announcement);

        // 设置状态
        if (StringUtils.isBlank(announcement.getStatus())) {
            announcement.setStatus("active");
        }

        // 设置时间
        LocalDateTime now = LocalDateTime.now();
        announcement.setCreatedAt(now);
        announcement.setUpdatedAt(now);

        // 保存通告
        announcementMapper.insert(announcement);

        // 清除缓存
        redisUtils.del(CacheConstants.ANNOUNCEMENT_LIST_CACHE);
        redisUtils.del(CacheConstants.HOME_DATA_CACHE);

        return announcement.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateAnnouncement(Long id, AnnouncementCreateParam param) {
        // 查询通告信息
        Announcement announcement = announcementMapper.selectById(id);
        if (announcement == null) {
            throw new ApiException("通告不存在");
        }

        // 更新通告
        if (StringUtils.isNotBlank(param.getTitle())) {
            announcement.setTitle(param.getTitle());
        }
        if (param.getContent() != null) {
            announcement.setContent(param.getContent());
        }
        if (StringUtils.isNotBlank(param.getStatus())) {
            announcement.setStatus(param.getStatus());
        }

        // 设置更新时间
        announcement.setUpdatedAt(LocalDateTime.now());

        // 更新通告
        boolean success = announcementMapper.updateById(announcement) > 0;

        // 清除缓存
        if (success) {
            redisUtils.del(CacheConstants.ANNOUNCEMENT_LIST_CACHE);
            redisUtils.del(CacheConstants.HOME_DATA_CACHE);
        }

        return success;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteAnnouncement(Long id) {
        // 查询通告信息
        Announcement announcement = announcementMapper.selectById(id);
        if (announcement == null) {
            throw new ApiException("通告不存在");
        }

        // 删除通告
        boolean success = announcementMapper.deleteById(id) > 0;

        // 清除缓存
        if (success) {
            redisUtils.del(CacheConstants.ANNOUNCEMENT_LIST_CACHE);
            redisUtils.del(CacheConstants.HOME_DATA_CACHE);
        }

        return success;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateAnnouncementStatus(Long id, String status) {
        // 查询通告信息
        Announcement announcement = announcementMapper.selectById(id);
        if (announcement == null) {
            throw new ApiException("通告不存在");
        }

        // 更新状态
        boolean success = announcementMapper.updateStatus(id, status) > 0;

        // 清除缓存
        if (success) {
            redisUtils.del(CacheConstants.ANNOUNCEMENT_LIST_CACHE);
            redisUtils.del(CacheConstants.HOME_DATA_CACHE);
        }

        return success;
    }
}
